<template>
  <div v-loading="loading">
    <el-splitter :resizable="false">
      <el-splitter-panel>
        <el-tabs
          @tab-change="loadData"
          tab-position="left"
          v-model="currentClass"
          :style="`height: ${tableHeight}px`"
        >
          <el-tab-pane
            v-for="cls in allDseClass"
            :key="cls.Pk"
            :name="cls.Pk"
            :label="cls.ClassName"
          >
            <el-table
              :border="true"
              :row-style="`height:${(tableHeight - 40) / 11}px`"
              :max-height="tableHeight"
              :data="tableData"
              style="width: 100%"
            >
              <el-table-column prop="Id" label="课序" width="60" />
              <el-table-column v-for="day in week" :key="day" :prop="day" :label="day">
                <template #default="scope">
                  <div style="width: 100%; display: flex; gap: 3px">
                    <CourseCard
                      v-for="t in scope.row[day]"
                      :key="t.Pk"
                      :id="t.Pk"
                      :teacher="t.Teacher._v"
                      :color="t.Color"
                      :name="t.Course._v"
                      :height="(tableHeight - 40) / 11 - 20"
                      :optional="t.Optional"
                      :style="`width: calc(100% / ${scope.row[day].length})`"
                      closeable
                      @close="remove(scope.row.Id, day, t.Pk)"
                    />
                  </div>
                  <draggable
                    @add="(e: any) => assigned(scope.row.Id, day, e)"
                    item-key="Id"
                    :group="{ name: 'g', pull: false, put: true }"
                  >
                    <template #item="{ element }"> </template>
                  </draggable>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-splitter-panel>
      <el-splitter-panel :size="150" style="padding-left: 10px">
        <el-scrollbar :height="`${tableHeight}px`">
          <draggable
            :group="{ name: 'g', pull: 'clone', put: false }"
            v-model="allCourse"
            item-key="Pk"
          >
            <template #item="{ element }">
              <div :data-id="element.Pk" style="margin-bottom: 10px">
                <CourseCard
                  :id="element.Pk"
                  :teacher="element.Teacher._v"
                  :color="element.Color"
                  :name="element.CourseName"
                  :height="50"
                  :optional="element.Optional"
                  style="width: 125px; cursor: move"
                />
              </div>
            </template>
          </draggable>
        </el-scrollbar>
      </el-splitter-panel>
    </el-splitter>
    <div v-loading="loading" class="my_opt_btn_pannel">
      <div style="text-align: left"></div>
      <div style="text-align: right; padding-right: 20px">
        <el-date-picker
          style="margin-right: 8px"
          v-model="dateRange"
          type="daterange"
          range-separator="|"
        />
        <el-button
          :disabled="!dateRange[0]"
          v-if="optUser.isAdm"
          type="primary"
          @click="buildSchedule"
          >生成课时计划</el-button
        >
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue'
import { listCourse } from '@/api/course'
import { listDseClass } from '@/api/dseclass'
import type { DseClassModel } from '@/type/DseClass'
import { useWindowSize } from '@vueuse/core'
import type { CourseModel } from '@/type/Course'
import draggable from 'vuedraggable'
import CourseCard from '@/components/CourseCard.vue'
import { safeAssign } from '@/utils/objUtils'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { ScheduleTemplateModel } from '@/type/ScheduleTemplate'
import {
  delScheduleTemplate,
  listScheduleTemplateByClass,
  saveScheduleTemplate,
} from '@/api/scheduleTemplate'
import { useUserStore } from '@/stores/user'
import { initFromTemplate } from '@/api/schedule'
import { dateFormat } from '@/utils/stringUtils'
import router from '@/router'
const optUser = useUserStore()
if (!optUser.isAdm) router.push('/401')

const currentClass = ref('')
const week = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
const winSize = useWindowSize()
const tableHeight = computed(() => winSize.height.value - 60 - 16 - 32 - 4) //60是MENU,16是PADDING,32是按钮区域，4是内容区和按钮区的距离
const loading = ref(false)
const allDseClass = ref<DseClassModel[]>([])
const allCourse = ref<CourseModel[]>([])
interface sch_template {
  Id: number
  Mon?: ScheduleTemplateModel[]
  Tue?: ScheduleTemplateModel[]
  Wed?: ScheduleTemplateModel[]
  Thu?: ScheduleTemplateModel[]
  Fri?: ScheduleTemplateModel[]
}
const tableData = ref<sch_template[]>([])
const dateRange = ref<Date[]>([])
onMounted(async () => {
  try {
    loading.value = true
    allDseClass.value = (await listDseClass({ pageSize: 10000 })).Data
    allCourse.value = (await listCourse({ pageSize: 10000 })).Data
    currentClass.value = allDseClass.value[0]?.Pk!
    loadData(allDseClass.value[0]?.Pk!)
  } finally {
    loading.value = false
  }
})
const loadData = async (name: string) => {
  tableData.value = []
  for (let i = 0; i < 11; i++) {
    const sch: sch_template = { Id: i + 1 }
    for (let j = 0; j < week.length; j++) {
      safeAssign(sch, week[j]!, [])
    }
    tableData.value.push(sch)
  }
  const s = (await listScheduleTemplateByClass(name)).Data
  s.forEach((r) => {
    const e = getScheduleTemplates(r.Seq!, week[r.WeekDay! - 1]!)
    e.push(r)
  })
}
const getScheduleTemplates = (seq: number, col: string) => {
  const row = tableData.value.find((t) => t.Id === seq)
  return (row as any)[col] as ScheduleTemplateModel[]
}
const assigned = async (rowNo: number, col: string, e: any) => {
  allCourse.value.find((r) => r.Pk === e.item.dataset.id)
  const old = getScheduleTemplates(rowNo, col)
  const c = allCourse.value.find((r) => r.Pk === e.item.dataset.id)
  if (old.length > 0 && (old[0]!.Optional !== 'Y' || c?.Optional !== 'Y')) {
    try {
      await ElMessageBox.confirm(`${col}的第${rowNo}节课已经有安排，是否确定要替换?`, '提示')
    } catch {
      return
    }
  }
  try {
    loading.value = true
    if (old.length > 0 && !(old[0]!.Optional === 'Y' && c?.Optional === 'Y')) {
      //除非原课程以及新加入的课程都是选修，否则要删除现在的安排
      old.forEach(async (o) => {
        await delScheduleTemplate(o.Pk!)
      })
      old.length = 0
    }
    const s = (
      await saveScheduleTemplate({
        DseClass: currentClass.value,
        WeekDay: week.indexOf(col) + 1,
        Color: c?.Color,
        Teacher: c?.Teacher,
        Course: c?.Pk,
        Seq: rowNo,
      })
    ).Data[0]
    old.push(s!)
    ElMessage.success('操作成功')
  } finally {
    loading.value = false
  }
}
const remove = async (rowNo: number, col: string, pk: string) => {
  try {
    loading.value = true
    await delScheduleTemplate(pk)
    const templates = getScheduleTemplates(rowNo, col)
    templates.splice(
      templates.findIndex((r) => r.Pk === pk),
      1,
    )
    ElMessage.success('操作成功')
  } finally {
    loading.value = false
  }
}
const buildSchedule = async () => {
  try {
    loading.value = true
    const start = dateFormat(dateRange.value[0]!)
    const end = dateFormat(dateRange.value[1]!)
    await initFromTemplate(currentClass.value, start, end)
    ElMessage.success('操作成功')
  } finally {
    loading.value = false
  }
}
</script>
